"""
def simple_gen():
    "简单的生成器函数"
    print("First yield")
    yield 1
    print("Second yield")
    yield 2
    print("Done")


# 创建生成器对象
g = simple_gen()
print(next(g))  # 输出: First yield \n 1
print(next(g))  # 输出: Second yield \n 2
# print(next(g))  # 会引发 StopIteration 异常

# 生成器可以用 for 循环遍历
for value in simple_gen():
    print(f"Got: {value}")
# 行转列
scores = [
    (85, 92, 78),  # 张三的成绩
    (76, 88, 95),  # 李四的成绩
    (90, 85, 92),  # 王五的成绩
]
chinese, math, english = zip(*scores)
for subject_scores in zip(*scores):
    print(subject_scores)
print("语文成绩:", chinese)  # (85, 76, 90)
print("数学成绩:", math)  # (92, 88, 85)
print("英语成绩:", english)  # (78, 95, 92)
from itertools import zip_longest

# 保留所有元素，用默认值填充
a = [1, 2, 3]
b = [4, 5]
for x, y in zip_longest(a, b, fillvalue=0):
    print(f"{x} + {y} = {x + y}")


# 输出:
# 1 + 4 = 5
# 2 + 5 = 7
# 3 + 0 = 3
class FileLineIterator:
    "文件行迭代器，自动管理文件资源"

    def __init__(self, filename):
        self.filename = filename
        self.file = None

    def __iter__(self):
        # 打开文件
        self.file = open(self.filename, "r", encoding="utf-8")
        return self

    def __next__(self):
        if self.file is None:
            raise RuntimeError("必须先调用 __iter__ 方法")

        line = self.file.readline()
        if not line:  # 文件结束
            self.file.close()
            raise StopIteration

        return line.strip()

    def __del__(self):
        "确保文件被关闭"
        if self.file and not self.file.closed:
            self.file.close()


# 使用示例
def process_file(filename):
    "处理文件内容"
    for line in FileLineIterator(filename):
        if line:  # 跳过空行
            print(f"处理: {line}")


# 更安全的使用方式
def safe_process_file(filename):
    "更安全的文件处理方式"
    try:
        with open(filename, "r", encoding="utf-8") as file:
            for line in file:
                line = line.strip()
                if line:
                    print(f"处理: {line}")
    except FileNotFoundError:
        print(f"文件 {filename} 不存在")
    except Exception as e:
        print(f"处理文件时出错: {e}")


# 使用
process_file("example.txt")
safe_process_file("example.txt")


class TreeNode:
    "树节点类"

    def __init__(self, value):
        self.value = value
        self.children = []

    def add_child(self, child):
        self.children.append(child)


class TreeIterator:
    "树的前序遍历迭代器"

    def __init__(self, root):
        self.stack = [root] if root else []

    def __iter__(self):
        return self

    def __next__(self):
        if not self.stack:
            raise StopIteration

        # 弹出当前节点
        node = self.stack.pop()

        # 将子节点逆序加入栈（保证前序遍历顺序）
        for child in reversed(node.children):
            self.stack.append(child)

        return node.value


# 构建示例树
#        A
#       / \
#      B   C
#     / \
#    D   E
root = TreeNode("A")
b = TreeNode("B")
c = TreeNode("C")
d = TreeNode("D")
e = TreeNode("E")

root.add_child(b)
root.add_child(c)
b.add_child(d)
b.add_child(e)

# 遍历树
print("前序遍历:")
for value in TreeIterator(root):
    print(value, end=" ")  # 输出: A B D E C
"""


def average_generator():
    """计算平均值的生成器"""
    total = 0
    count = 0
    average = 0
    while True:
        new_value = yield average
        if new_value is None:
            break
        total += new_value
        count += 1
        average = total / count
        print("---------")
    print("生成器已关闭")
    return average


# 使用平均值生成器
avg_gen = average_generator()
next(avg_gen)  # 启动生成器
print(avg_gen.send(10))  # 输出: 10.0
print(avg_gen.send(20))  # 输出: 15.0
print(avg_gen.send(30))  # 输出: 20.0

# 发送 None 触发结束并捕获 return 的值
try:
    avg_gen.send(None)
except StopIteration as e:
    print("最终平均值:", e.value)  # e.value 是 return 返回的 average
